<template>
  <a-drawer width="55%" :label-col="4" :wrapper-col="14" :visible="open" @close="onClose">
    <a-divider orientation="left">
      <b>{{ formTitle }}</b>
    </a-divider>
    <a-form-model ref="form" :model="form" :rules="rules">
      <a-form-item label="姓名" prop="name" :required="true">
        <a-select placeholder="请选择姓名" v-model="form.name" style="width: 100%" allow-clear show-search
          :filter-option="customFilterOption">
          <a-select-option v-for="(d, index) in kehuList" :key="index" :value="d.name">
            {{ d.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-model-item label="出库日期" prop="buyTime">
        <a-date-picker style="width: 100%" v-model="form.buyTime" :defaultValue="moment(new Date(), 'YYYY-MM-DD')"
          valueFormat="YYYY-MM-DD" format="YYYY-MM-DD" allow-clear />
      </a-form-model-item>
      <a-divider orientation="left">
        <b>出库明细</b>
      </a-divider>
      <!-- 表格组建 -->
      <sub-table-form ref="subTable" :list="subList" @add="handleAdddxmChukuDetail"
        @delete="handleDeletedxmChukuDetail" />

      <a-form-model-item label="支付状态" prop="ispay">
        <a-radio-group v-model="form.ispay" button-style="solid">
          <a-radio-button v-for="(d, index) in ispayOptions" :key="index" :value="d.value">{{ d.label }}</a-radio-button>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item v-if="form.ispay != 'N'" label="实收金额" prop="shishou">
        <a-input-number style="width:100%" v-model="form.shishou" placeholder="请输入实收金额" allow-clear />
      </a-form-model-item>
      <a-form-model-item label="备注" prop="remark">
        <a-input v-model="form.remark" placeholder="请输入内容" type="textarea" allow-clear />
      </a-form-model-item>

      <div class="bottom-control">
        <a-space>
          <a-button type="primary" :loading="submitLoading" @click="submitForm">
            保存
          </a-button>
          <a-button type="dashed" @click="cancel">
            取消
          </a-button>
        </a-space>
      </div>
    </a-form-model>
  </a-drawer>
</template>

<script>
import { getChuku, addChuku, updateChuku } from '@/api/system/chuku'
import SubTableForm from './SubTableForm'
import moment from 'moment';
import { listKehu } from '@/api/system/kehu'
import 'moment/locale/zh-cn';
import pinyin from 'js-pinyin';

export default {
  name: 'CreateForm',
  props: {
    ispayOptions: {
      type: Array,
      required: true
    }
  },
  components: {
    SubTableForm
  },
  data() {
    return {

      moment,
      // 客户列表
      kehuList: [],
      submitLoading: false,
      subList: [],
      formTitle: '',
      // 表单参数
      form: {
        id: null,

        name: null,

        heji: null,

        shishou: null,

        ispay: 'N',

        remark: null,

        buyTime: null,

        createTime: null,

        createBy: null

      },
      // 1增加,2修改
      formType: 1,
      open: false,
      rules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'change' }
        ],

        ispay: [
          { required: true, message: '支付状态不能为空', trigger: 'blur' }
        ],

        buyTime: [
          { required: true, message: '出库时间不能为空', trigger: 'input' }
        ],
        shishou: [
          { required: true, message: '实收不能为空', trigger: 'input' }
        ]
      }
    }
  },
  filters: {
  },
  created() {
    this.getKehuList();
  },
  computed: {

  },
  watch: {
  },
  mounted() {
  },
  methods: {


    // 自定义过滤选项的方法
    // 自定义过滤选项的方法
    customFilterOption(input, option) {
      // 获取选项的文本值
      const optionText = option.componentOptions.children[0].text;
      // 将输入的内容转换为小写
      const inputValue = input.toLowerCase();

      // alert(this.isFirstLetterMatch(inputValue, optionText))
      // 判断输入内容是否匹配选项的汉字、首字母或拼音
      return (
        this.isMatch(optionText, inputValue) || // 匹配汉字
        this.isFirstLetterMatch(inputValue, optionText) || // 匹配首字母
        this.isPinyinMatch(inputValue, optionText) // 匹配拼音
      );
    },

    // 判断输入内容是否匹配选项的汉字
    isMatch(optionText, inputValue) {
      // 将选项文本转换为小写
      const text = optionText.toLowerCase();
      // 判断输入内容是否在选项文本中
      return text.includes(inputValue);
    },

    // 判断输入内容是否匹配选项的首字母
    isFirstLetterMatch(input, optionText) {
      // 将选项文本转换为小写
      const text = optionText.toLowerCase();
      // 将输入内容转换为小写
      const inputValue = input.toLowerCase();
      // 获取选项文本的每个字的首字母（不区分大小写）
      const firstLetters = text.split('').map(char => pinyin.getCamelChars(char)[0].toLowerCase()).join('');
      // 判断输入内容是否与选项文本的首字母匹配
      return firstLetters.includes(inputValue);
    },

    // 判断输入内容是否匹配选项的拼音
    isPinyinMatch(input, optionText) {
      // 将选项文本转换为拼音
      const pinyinText = pinyin.getFullChars(optionText).toLowerCase();
      // 将输入内容转换为拼音
      const pinyinInput = pinyin.getFullChars(input).toLowerCase();
      // 判断输入内容是否在选项文本的拼音中
      return pinyinText.includes(pinyinInput);
    },

    onClose() {
      this.open = false
      this.subList = []
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
      this.subList = []
    },
    // 表单重置
    reset() {
      this.formType = 1
      this.form = {
        id: null,

        name: null,

        heji: null,

        shishou: null,

        ispay: null,

        remark: null,

        buyTime: moment(new Date(), 'YYYY-MM-DD'),

        createTime: null,

        createBy: null

      }
    },

    // 获取客户列表
    getKehuList() {
      listKehu({ pageSize: '9999999' }).then(response => {
        this.kehuList = response.rows
      })
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.formType = 1
      this.open = true
      this.formTitle = '添加'
    },
    /** 新增子项操作 */
    handleAdddxmChukuDetail(row) {
      this.subList.push(row)
    },
    /** 删除子项操作 */
    handleDeletedxmChukuDetail(index, indexs) {
      if (index !== undefined) {
        this.subList.splice(index, 1)
        return
      }
      indexs.forEach(item => {
        this.subList.splice(item, 1)
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row, ids) {
      this.reset()
      this.formType = 2
      const id = row ? row.id : ids
      getChuku(id).then(response => {
        this.form = response.data
        this.subList = response.data.dxmChukuDetailList
        this.open = true
        this.formTitle = '修改'
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log(this.form.name)
      if (null == this.form.name || this.form.name == "") {
        this.$message.error(
          '姓名不能为空，请选择姓名',
          4
        );
        return false
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.ispay == 'N') {
            this.form.shishou = 0
          }
          this.submitLoading = true
          // 计算金额总和
          const heji = this.subList.reduce((acc, item) => acc + parseFloat(item.allprice || 0), 0);
          this.form.heji = heji.toFixed(2); // 保留两位小数
          this.form.dxmChukuDetailList = this.subList
          if (this.form.id !== undefined && this.form.id !== null) {
            updateChuku(this.form).then(response => {
              this.$message.success(
                '修改成功',
                3
              )
              this.reset()
              this.subList = []
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            addChuku(this.form).then(response => {
              this.$message.success(
                '新增成功',
                3
              )
              this.reset()
              this.subList = []
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.submitLoading = false
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
